package com.heima.controller;


import com.heima.common.PageResult;
import com.heima.pojo.Sku;
import com.heima.pojo.dto.SkuDTO;
import com.heima.pojo.vo.SkuVO;
import com.heima.service.SkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@RestController
@RequestMapping("/api/vm-service/sku")
@Slf4j
public class SkuController {
    @Autowired
    SkuService skuService;

    //商品新增
    @PostMapping
    public Boolean saveSku(@RequestBody SkuDTO skuDTO){
        log.info("商品新增 {}", skuDTO);
        return skuService.saveSku(skuDTO);
    }

    //商品分页查询
    @GetMapping("/search")
    public PageResult<SkuVO> page(SkuDTO skuDTO) {
        //log.info("分页查询商品: {}", skuDTO);
        return skuService.page(skuDTO);
    }


    //商品修改
    @PutMapping("/{skuId}")
    public Boolean update(@PathVariable Long skuId, @RequestBody SkuDTO skuDTO) {
        log.info("修改商品: {}   {}", skuId, skuDTO);

        return skuService.update(skuId, skuDTO);
    }


    //商品图片上传
    @PostMapping("/fileUpload")
    public String fileUpload(@RequestParam("fileName") MultipartFile fileName) {
        // 检查文件是否为空
        if (fileName == null || fileName.isEmpty()) {
            log.warn("上传文件为空");
            return "文件上传失败：文件为空";
        }

        try {
            // 获取文件原始名称
            String originalFilename = fileName.getOriginalFilename();
            log.info("商品图片上传: 文件名={}, 大小={}字节", originalFilename, fileName.getSize());
            // 确定文件保存路径 (src/main/resources/static/images)
            String uploadDir = "src/main/resources/static/images/";
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 生成唯一文件名
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;

            // 保存文件到指定目录
            Path targetLocation = Paths.get(uploadDir + uniqueFilename);
            Files.copy(fileName.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            // 返回文件访问路径
            String fileUrl = "/images/" + uniqueFilename;
            log.info("文件上传成功: {}", fileUrl);

            return fileUrl;
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return "文件上传失败：" + e.getMessage();
        } catch (Exception e) {
            log.error("文件上传异常", e);
            return "文件上传异常：" + e.getMessage();
        }
    }
}


